 package edu.ccut.saturn.component.loader;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.Element;
import org.osgi.framework.Bundle;

import edu.ccut.saturn.component.ILogger;
import edu.ccut.saturn.component.SaturnComponentException;
import edu.ccut.saturn.component.SaturnLoggerManager;
import edu.ccut.saturn.component.impl.SaturnBundleFilterInfo;
import edu.ccut.saturn.component.impl.SaturnFilterInfo;
import edu.ccut.saturn.component.xml.Dom4jUtils;

/**
 * 加载解析过滤器配置文件
 * @author xiyue1314
 *
 */
public class FilterInfoLoader {
	
	private static final String LOGGER_KEY_LOAD_BUNDLE = SaturnLoggerManager.LOGGER_KEY_LOAD_BUNDLE;
	
	protected static ILogger logger = SaturnLoggerManager.getInstance()
	.getSaturnLogger(LOGGER_KEY_LOAD_BUNDLE);
	
	public static SaturnBundleFilterInfo loadSaturnBundleFilterInfo(Bundle bundle, URL url) throws SaturnComponentException{
		
		InputStream in = null;
		try {		
			in = url.openStream();
			return loadSaturnBundleFilterInfo(bundle, in);

		} catch (IOException e) {
			throw new SaturnComponentException(
					"load filter config file failed in bundle [key="
							+ bundle.getSymbolicName() + "]", e);
		} finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (IOException e) {
				logger.error(
						"Found IOException! load filter config file failed in bundle [key="
								+ bundle.getSymbolicName() + "]", e);
			}
		}
	}
	
	@SuppressWarnings("unchecked")
	public static SaturnBundleFilterInfo loadSaturnBundleFilterInfo(Bundle bundle,
			InputStream in) throws SaturnComponentException{

		Document document = Dom4jUtils.getDocment(in);
		Element root = document.getRootElement();
		String symbolicname = bundle.getSymbolicName();
		Element filtersElement = root.element("filters");
		if (filtersElement != null) {
			List<Element> filters = filtersElement.elements("filter");
			//List<SaturnFilterInfo> saturnFilterInfos= new ArrayList<SaturnFilterInfo>();
			Map<String,SaturnFilterInfo> filterInfoMap = new HashMap<String,SaturnFilterInfo>();
			for(Element filter:filters){
				String className = filter.attributeValue("className").trim();
				String path = filter.attributeValue("path").trim();
				SaturnFilterInfo saturnFilterInfo = new SaturnFilterInfo(className,path);
				filterInfoMap.put(path, saturnFilterInfo);
			}
			SaturnBundleFilterInfo saturnBundleFilterInfo = new SaturnBundleFilterInfo(symbolicname);
//			Element errorUrlElement = root.element("error-url");
//			String errorUrl = errorUrlElement.getText().trim();
			saturnBundleFilterInfo.setFilterInfoMap(filterInfoMap);
//			saturnBundleFilterInfo.setErrorUrl(errorUrl);
			return saturnBundleFilterInfo;
		}
		return null;
	}
}
